package com.qkjia.springcloud.hystrixservice.filter;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * Description:
 *
 * @author JourWon
 * @date 2019/12/19 13:49
 *这里我们通过使用过滤器，在每个请求前后初始化和关闭HystrixRequestContext来解决该问题：
 *
 * java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext?
 * 我们可以编写一个过滤器，在过滤器中，在有请求发来时，初始化一个HystrixRequestContext对象。过滤器代码如下：
 */
@Component//组件
@WebFilter(urlPatterns = "/*", asyncSupported = true)//Web过滤器： asyncSupported 开启异步，urlPatterns配置Filter过滤路径
public class HystrixRequestContextFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        //初始化请求

        try {
            filterChain.doFilter(servletRequest, servletResponse);//过滤
        } finally {
            context.close();//关闭
        }
    }

}
